<template>
  <div class="left">
    <!-- 登录表单 -->
    <el-card class="login-card">
      <template #header>
        <div class="login-card__header">
          <span>登录</span>
        </div>
      </template>
      <el-form
        class="login-form"
        :model="loginForm"
        label-width="auto"
        label-position="right"
      >
        <el-form-item label="录像机 IP">
          <el-input v-model="loginForm.ip" />
        </el-form-item>
        <el-form-item label="录像机端口">
          <el-input v-model="loginForm.port" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="loginForm.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="loginForm.password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onLogin">登录</el-button>
          <el-button @click="onLogout">注销</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- IP 通道表格 -->
    <el-card class="ip-channel-card">
      <template #header>
        <div class="ip-channel__header">
          <span>通道状态</span>
        </div>
      </template>

      <el-table
        :data="ipChannelList"
        @row-click="onRowClicked"
        style="width: 100%; font-size: 12px"
      >
        <el-table-column prop="port" label="通道号" />
        <el-table-column prop="name" label="通道名称" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'true' ? 'primary' : 'danger'">
              {{ scope.row.status === "true" ? "在线" : "离线" }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="log-card">
      <template #header>
        <div class="log-card__header">
          <span>日志</span>
        </div>
      </template>
      <el-input type="textarea" autosize v-model="log" readonly></el-input>
    </el-card>
  </div>

  <div class="center">
    <div id="divPlugin"></div>
  </div>

  <div class="right">
    <el-card>
      <el-date-picker
        v-model="datetimeRange"
        type="datetimerange"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        format="YYYY-MM-DD HH:mm:ss"
        date-format="YYYY/MM/DD"
        value-format="YYYY-MM-DD HH:mm:ss"
        time-format="hh:mm:ss"
      />
      <el-button @click="onSearchBtnClicked">查询</el-button>
    </el-card>

    <el-table class="video-form" :data="videoList">
      <el-table-column prop="fileName" label="文件名" />
      <el-table-column prop="startTime" label="开始时间" />
      <el-table-column prop="endTime" label="结束时间" />
      <el-table-column fixed="right" min-width="120" label="操作">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="onDownloadBtnClicked(scope.$index)"
          >
            下载
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="onPlaybackBtnClicked(scope.$index)"
          >
            回放
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="onStopBtnClicked()"
          >
            停止
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref, reactive, watch } from "vue";

const log = ref("");

const szDeviceIdentify = ref("");

const loginForm = reactive({
  ip: "172.16.0.241",
  port: 80,
  username: "admin",
  password: "Aa123456",
});

const ipChannelList = reactive([]);

const datetimeRange = ref([]);

const videoList = reactive([]);

const selectedChannelRow = ref(1);

const showLog = (content) => {
  const now = new Date();
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");

  log.value += `${hours}:${minutes}:${seconds} - ${content}\n`;
};

const initPlugin = () => {
  WebVideoCtrl.I_InitPlugin({
    bDebugMode: true,
    cbEvent: (iEventType, iParam1, iParam2) => {
      console.log("------------->", iEventType);
    },
    cbInitPluginComplete: () => {
      WebVideoCtrl.I_InsertOBJECTPlugin("divPlugin").then(
        () => {
          showLog("插件初始化成功！");

          WebVideoCtrl.I_CheckPluginVersion().then((flag) => {
            if (flag) {
            }
          });
        },
        (error) => {
          console.log("插入插件失败！原因：", error);
        }
      );
    },
  });
};

const onLogin = () => {
  WebVideoCtrl.I_Login(
    loginForm.ip,
    1,
    loginForm.port,
    loginForm.username,
    loginForm.password,
    {
      timeout: 3000,
      success: (xmlDoc) => {
        showLog("登录设备成功！");

        szDeviceIdentify.value = loginForm.ip + "_" + loginForm.port;

        setTimeout(() => {
          getIpChannelList();
        }, 500);
      },
      error: (error) => {
        console.log("登录失败，原因：", error);
      },
    }
  );
};

const onLogout = () => {
  if (null == szDeviceIdentify.value) {
    return;
  }

  WebVideoCtrl.I_Logout(szDeviceIdentify.value).then(
    () => {
      showLog("注销成功！");

      ipChannelList.length = 0;
    },
    (error) => {
      console.log("注销失败，原因：", error);
    }
  );
};

const getIpChannelList = () => {
  if (null == szDeviceIdentify.value) {
    return;
  }

  WebVideoCtrl.I_GetDigitalChannelInfo(szDeviceIdentify.value, {
    success: (xmlDoc) => {
      const channelStatusList = xmlDoc.getElementsByTagName(
        "InputProxyChannelStatus"
      );

      for (let i = 0; i < channelStatusList.length; i++) {
        const channelStatus = channelStatusList[i];

        const port = channelStatus.getElementsByTagName("id")[0]?.textContent;

        const descriptor = channelStatus.getElementsByTagName(
          "sourceInputPortDescriptor"
        )[0];

        const name = descriptor.getElementsByTagName("name")[0].textContent;
        const status = descriptor.getElementsByTagName("online")[0].textContent;

        ipChannelList.push({
          port,
          name,
          status,
        });
      }
    },
    error: (error) => {
      console.log("获取数字通道失败！原因：", error);
    },
  });
};

const onRowClicked = (row, column, event) => {
  selectedChannelRow.value = row.port;
};

const onSearchBtnClicked = () => {
  const startTime = datetimeRange.value[0];
  const endTime = datetimeRange.value[1];

  if (startTime > endTime) {
    return;
  }

  videoList.length = 0;

  getVideoList(selectedChannelRow.value, startTime, endTime);
};

const processSearchMatchItems = (searchMatchItems) => {
  searchMatchItems.forEach((item) => {
    // 获取 rtsp url
    const playbackURI = item.querySelector("playbackURI").textContent;

    if (!playbackURI.includes("name=")) {
      return;
    }

    const startTime = item
      .querySelector("startTime")
      .textContent.replace("T", " ")
      .replace("Z", "");

    const endTime = item
      .querySelector("endTime")
      .textContent.replace("T", " ")
      .replace("Z", "");

    const fileName = playbackURI.substring(
      playbackURI.indexOf("name=") + 5,
      playbackURI.indexOf("&size=")
    );

    videoList.push({
      fileName,
      startTime,
      endTime,
      playbackURI,
    });
  });
};

const getVideoList = (channelNum = 1, startTime, endTime, searchPos = 0) => {
  if (null == szDeviceIdentify) {
    return;
  }

  WebVideoCtrl.I_RecordSearch(
    szDeviceIdentify.value,
    channelNum,
    startTime,
    endTime,
    {
      iSearchPos: searchPos,
      success: (xmlDoc) => {
        const status = xmlDoc.querySelector("responseStatusStrg").textContent;
        const searchMatchItems = xmlDoc.querySelectorAll("searchMatchItem");

        if (status === "MORE") {
          processSearchMatchItems(searchMatchItems); // 处理搜索结果
          getVideoList(channelNum, startTime, endTime, searchPos + 40); // 继续搜索
        } else if (status === "OK") {
          processSearchMatchItems(searchMatchItems);
        } else if (status === "NO MATCHES") {
          console.log("没有录像文件");
        }
      },
      error: (error) => {
        console.log("查询历史视频文件失败，原因：", error);
      },
    }
  );
};

const onDownloadBtnClicked = (index) => {
  const video = videoList[index];

  const playbackURI = video.playbackURI;
  const fileName = video.fileName;

  downloadVideoByName(playbackURI, fileName);
};

const onPlaybackBtnClicked = (index) => {
  const video = videoList[index];
  const startTime = video.startTime;
  const endTime = video.endTime;

  if (!szDeviceIdentify.value) {
    return null;
  }

  WebVideoCtrl.I_StartPlayback(szDeviceIdentify.value, {
    szStartTime: startTime,
    szEndTime: endTime,
    iChannelID: selectedChannelRow.value,
    success: function () {
      showLog("开始回放...");
    },
    error: function (error) {
      showLog(
        `回放失败！错误码：${error.errorCode}，错误信息：${error.errorMsg}`
      );
    },
  });
};

const onStopBtnClicked = () => {
  WebVideoCtrl.I_Stop({
    success: function () {
      showLog("停止回放成功！");
    },
  });
};

const downloadVideoByName = (playbackURI, fileName) => {
  if (!szDeviceIdentify.value) {
    return null;
  }

  WebVideoCtrl.I_StartDownloadRecord(
    szDeviceIdentify.value,
    playbackURI,
    fileName
  ).then(
    (iDownloadID) => {},
    (error) => {
      console.log("下载录像文件失败，原因：", error);
    }
  );
};

onMounted(() => {
  initPlugin();
});

onBeforeUnmount(() => {});
</script>

<style scoped></style>
